<template>
  <div id="content" :style="{height:contentHeight+'px'}">
    <Card class="r-n-fs-c">
      <Select style="width: 240px;" v-model="page.projectId" @on-change="searchOrthographicImage" clearable placeholder="所属项目">
        <Option v-for="item in projectList" :key="item.id" :value="item.id">{{item.projectName}}</Option>
      </Select>
      <Select style="width: 240px;margin-left: 5px;" v-model="searchKey" clearable @on-clear="searchKeyClear" placeholder="精确匹配查询参数">
        <Option v-for="item in searchParamList" :key="item.key" :value="item.key">{{item.show}}</Option>
      </Select>
      <Input v-model="searchValue" placeholder="请输入查询内容..." clearable style="width: 300px;margin-left: 5px;" />
      <Button @click="selectPageList(page)" type="primary" style="width: 100px;margin-left: 5px;">查询</Button>
      <Button @click="orthographicImageAdd()" type="primary" style="width: 150px;margin-left: 5px;">添加正射访问地址</Button>
      <Button @click="orthographicImageGroupAdd()" type="primary" style="width: 150px;margin-left: 5px;">添加分组</Button>
    </Card>
    <Divider/>
    <div>
      <Table id="card-list-info-table" class="table" stripe
             border
             show-header
             highlight-row
             :loading="isLoading"
             :columns="tableColumns"
             :data="dataList">
      </Table>
      <Divider/>
      <Card style="margin-bottom: 15px;">
        <Page class="r-w-c-c"
              style="width: 100%"
              class-name="card-list-info-page"
              :total="page.total"
              :current="page.pageNum"
              :page-size="page.pageSize"
              @on-change="onPageChange"
              @on-page-size-change="onPageSizeChange"
              show-elevator
              show-sizer
              show-total/>
      </Card>
    </div>
    <Modal v-model="modalTip" width="360">
      <p slot="header" style="color:#f60;text-align:center">
        <Icon type="ios-information-circle"></Icon>
        <span>操作确认</span>
      </p>
      <div style="text-align:center">
        <p>{{ modalTipContent }}</p>
      </div>
      <div slot="footer">
        <Button type="error" size="large" long :loading="modalLoading" @click="modalTipOk">确认操作</Button>
      </div>
    </Modal>
    <Modal v-model="isOrthographicImageAddShow" :title="modalTitle">
      <Form ref="selectFormRule" :rules="ruleValidate" :model="selectForm"
            style="margin-left: 0;width: 100%;">
        <label class="r-n-fs-c item-input">
          <span class="item-input-span">名称</span>
          <FormItem prop="name">
            <Input placeholder="正射名称" v-model="selectForm.name"/>
          </FormItem>
        </label>
        <label class="r-n-fs-c item-input">
          <span class="item-input-span">URL</span>
          <FormItem prop="url">
            <Input placeholder="正射URL路径" v-model="selectForm.url"/>
          </FormItem>
        </label>
        <label class="r-n-fs-c item-input" >
          <span class="item-input-span">所属项目</span>
          <Select style="width: 100%" v-model="selectForm.projectId" clearable placeholder="所属项目">
            <Option v-for="item in projectList" :key="item.id" :value="item.id">{{item.projectName}}</Option>
          </Select>
        </label>
        <label class="r-n-fs-c item-input" v-if="selectForm.projectId !== null && selectForm.projectId !== undefined">
          <span class="item-input-span">所属管线</span>
          <Select style="width: 100%" v-model="selectForm.pipelineId" clearable placeholder="所属管线">
            <Option v-for="item in pipelineSelectList" :key="item.id" :value="item.id">{{item.name}}</Option>
          </Select>
        </label>
        <label class="r-n-fs-c item-input" v-if="selectForm.projectId !== null && selectForm.projectId !== undefined">
          <span class="item-input-span">所属分组</span>
          <Select style="width: 100%" v-model="selectForm.pid" clearable placeholder="所属分组">
            <Option v-for="item in orthographicImageGroupSelectList" :key="item.id" :value="item.id">{{item.name}}</Option>
          </Select>
        </label>
      </Form>
      <div slot="footer">
        <Button type="text" @click="isOrthographicImageAddShow=false">取消</Button>
        <Button type="primary" @click="modalOk()">提交</Button>
      </div>
    </Modal>
    <Modal v-model="isOrthographicImageGroupAddShow" :title="modalTitle">
      <Form ref="selectGroupFormRule" :rules="ruleValidateGroup" :model="selectForm"
            style="margin-left: 0;width: 100%;">
        <label class="r-n-fs-c item-input">
          <span class="item-input-span">分组名称</span>
          <FormItem prop="name">
            <Input placeholder="分组名称" v-model="selectForm.name"/>
          </FormItem>
        </label>
        <label class="r-n-fs-c item-input" >
          <span class="item-input-span">所属项目</span>
          <Select style="width: 100%" v-model="selectForm.projectId" clearable placeholder="所属项目">
            <Option v-for="item in projectList" :key="item.id" :value="item.id">{{item.projectName}}</Option>
          </Select>
        </label>
      </Form>
      <div slot="footer">
        <Button type="text" @click="isOrthographicImageGroupAddShow=false">取消</Button>
        <Button type="primary" @click="modalOk()">提交</Button>
      </div>
    </Modal>

  </div>
</template>

<script>

import {mapGetters, mapState} from "vuex"
import axios from "axios";
import {Request} from "@/global/config";

export default {
  name: "OrthographicImage",
  computed: {
    ...mapState(["url", "host", "resourceHost", "realSideWidth","projectList"]),
    ...mapGetters(["contentWidth", "contentHeight"]),
  },
  data() {
    return {
      //搜索框对应字段名称
      searchKey: 'name',
      //搜索框输入值
      searchValue: null,
      //表格加载中状态是否展示
      isLoading: false,
      //添加正射地址
      isOrthographicImageAddShow: false,
      //添加正射组地址
      isOrthographicImageGroupAddShow: false,
      //操作确认提示框是否显示
      modalTip: false,
      //操作确认提示框显示内容
      modalTipContent: null,
      //操作确认提示框点击确认后按钮加载中状态是否显示
      modalLoading: false,
      //是否正在改变分页大小
      isPageSizeChanging: false,
      //弹出框标题
      modalTitle: '添加分组',
      //二层弹出框标题
      modalTitleData: null,
      //弹出框标题集合
      operatorType: ['添加分组','添加正射URL','删除正射/分组','修改正射URL','修改分组'],
      //正射表单信息数据校验
      ruleValidate: {
        name: [
          {required: true, type: 'string', message: '正射标记名称不能为空', trigger: 'change'},
          { min: 2, message: '正射标记名称不能少于2个字符', trigger: 'change'},
          { max: 20, message: '正射标记名称不能超过20个字符', trigger: 'change'}
        ],
        url: [
          {required: true, type: 'string', message: 'URL不能为空', trigger: 'change'},
          { min: 2, message: 'URL不能少于2个字符', trigger: 'change'},
          { max: 100, message: 'URL不能超过100个字符', trigger: 'change'}
        ]
      },
      //正射组表单信息数据校验
      ruleValidateGroup: {
        name: [
          {required: true, type: 'string', message: '正射分组名称不能为空', trigger: 'change'},
          { min: 2, message: '正射分组名称不能少于2个字符', trigger: 'change'},
          { max: 20, message: '正射分组名称不能超过20个字符', trigger: 'change'}
        ]
      },
      //头信息
      headers: {
        'u-projectId': null,
        'u-uid': null,
        'u-token': null,
      },
      //正射组集合
      orthographicImageGroupList:[],
      //正射组选择集合
      orthographicImageGroupSelectList:[],
      //操作参数集合
      selectForm: {
        id: null,
        pid: null,
        name: null,
        url: null,
        pipelineId: null,
        projectId: null
      },
      //分页查询参数
      page:{
        total: 0,
        pageSize: 10,
        pageNum: 1,
        descParams:'id',
        pid: null
      },
      //列表结构
      tableColumns: [
        {
          title: 'ID',
          key: 'id',
          width: 100,
          minWidth: 100,
          resizable: true,
          align: "center",
          ellipsis: true,
          sortable: true,
        },
        {
          title: '名称',
          key: 'name',
          resizable: true,
          width: 150,
          minWidth: 100,
          align: "center"
        },
        {
          title: 'URL',
          key: 'url',
          resizable: true,
          width: 500,
          minWidth: 150,
          align: "center",
          render:function (createElement,data){
            let {url} = data.row;
            if (url !== null && url !== undefined){
              return createElement('span',[url])
            }else {
              return createElement('span',"-")
            }
          }
        },
        {
          title: '所属管线编号',
          key: 'pipelineId',
          resizable: true,
          width: 130,
          align: "center",
          render:function (createElement,data){
            let {pipelineId} = data.row;
            if (pipelineId !== null && pipelineId !== undefined){
              return createElement('span',[pipelineId])
            }else {
              return createElement('span',"-")
            }
          }
        },
        {
          title: '分组编号',
          key: 'pid',
          resizable: true,
          minWidth: 130,
          align: "center",
          render:function (createElement,data){
            let {pid} = data.row;
            if (pid !== null && pid !== undefined){
              return createElement('span',[pid])
            }else {
              return createElement('span',"-")
            }
          }
        },
        {
          title: '所属项目',
          key: 'projectId',
          resizable: true,
          width: 200,
          align: "center",
          render: Request.projectNameRender
        },
        {
          title: '操作',
          resizable: true,
          minWidth: 240,
          align: "center",
          render: this.operatorRenderFunction
        }
      ],
      //列表数据
      dataList: [],
      //管线集合
      pipelineList: [],
      //管线选择集合
      pipelineSelectList: [],
      //精确匹配参数集合
      searchParamList: [
        {
          key: "id",
          show: "ID",
        },
        {
          key: "name",
          show: "名称",
        }
      ]
    }
  },
  watch: {
    //添加正射窗口是否显示状态变化事件
    isOrthographicImageAddShow:function (e) {
      if (!e){
        this.$refs['selectFormRule'].resetFields();
        this.$refs['selectGroupFormRule'].resetFields();
      }
    },
    //添加正射组窗口是否显示状态变化事件
    isOrthographicImageGroupAddShow:function (e) {
      if (!e){
        this.$refs['selectFormRule'].resetFields();
        this.$refs['selectGroupFormRule'].resetFields();
      }
    },
    //弹出框项目选择下拉列表项目ID变化事件
    'selectForm.projectId':function(e) {
      this.orthographicImageGroupSelectList = [];
      //正射组下拉列表变为所属项目下的所有正射组
      for (let item of this.orthographicImageGroupList) {
        if (e === undefined || item.projectId === e){
          this.orthographicImageGroupSelectList.push(item);
        }
      }
      if(this.orthographicImageGroupSelectList.find(((value) =>  value['id'] === this.selectForm['pid'])) === undefined){
        this.selectForm['pid'] = null;
      }
      this.pipelineSelectList = [];
      //管线下拉列表变为所属项目下的所有管线
      for (let item of this.pipelineList) {
        if (e === undefined || item.projectId === e){
          this.pipelineSelectList.push(item);
        }
      }
      if(this.pipelineSelectList.find(((value) =>  value['id'] === this.selectForm['pipelineId'])) === undefined){
        this.selectForm['pipelineId'] = null;
      }
    }
  },
  mounted: function () {
    this.selectPageList(this.page);
    this.selectGroupList();
    this.selectPipelineList();
  },
  methods: {
    //显示正射上传交互框
    orthographicImageGroupAdd(){
      this.modalTitle = this.operatorType[0];
      this.isOrthographicImageGroupAddShow = true;
    },
    //显示添加正射交互框
    orthographicImageAdd(){
      this.modalTitle = this.operatorType[1];
      this.isOrthographicImageAddShow = true;
    },
    //弹出框确认事件
    modalOk(){
      let isValidate = false;
      if (this.selectForm.projectId === null || this.selectForm.projectId === undefined){
        isValidate = false;
        this.$Message.error('所属项目未选择...');
        return;
      }
      if (this.modalTitle === this.operatorType[0]){
        this.$refs['selectGroupFormRule'].validate((valid) => {
          if (valid) {
            isValidate = true;
          }
        })
        if (!isValidate) {
          return;
        }
        this.insertOrthographicImageGroup(this.selectForm);
      }else if (this.modalTitle === this.operatorType[4]){
        this.$refs['selectGroupFormRule'].validate((valid) => {
          if (valid) {
            isValidate = true;
          }
        })
        if (!isValidate) {
          return;
        }
        this.updateOrthographicImageGroup(this.selectForm);
      }else if (this.modalTitle === this.operatorType[1]){
        if (this.selectForm.pipelineId === null || this.selectForm.pipelineId === undefined){
          isValidate = false;
          this.$Message.error('所属管线未选择...');
          return;
        }
        if (this.selectForm.pid === null || this.selectForm.pid === undefined){
          isValidate = false;
          this.$Message.error('所属分组未选择...');
          return;
        }
        this.$refs['selectFormRule'].validate((valid) => {
          if (valid) {
            isValidate = true;
          }
        })
        if (!isValidate) {
          return;
        }
        this.insertOrthographicImage(this.selectForm);
      }else if (this.modalTitle === this.operatorType[3]){
        if (this.selectForm.pipelineId === null || this.selectForm.pipelineId === undefined){
          isValidate = false;
          this.$Message.error('所属管线未选择...');
          return;
        }
        if (this.selectForm.pid === null || this.selectForm.pid === undefined){
          isValidate = false;
          this.$Message.error('所属分组未选择...');
          return;
        }
        this.$refs['selectFormRule'].validate((valid) => {
          if (valid) {
            isValidate = true;
          }
        })
        if (!isValidate) {
          return;
        }
        this.updateOrthographicImage(this.selectForm);
      }
    },
    //分页搜索正射列表
    searchOrthographicImage(){
      this.page.pageNum = 1;
      this.selectPageList(this.page);
    },
    //清除搜索框搜索值
    searchKeyClear(){
      let self = this;
      self.searchValue = null;
    },
    //页数改变事件
    onPageChange(changedPage) {
      this.page.pageNum = changedPage;
      !this.isPageSizeChanging ? this.selectPageList(this.page) : {};
    },
    //单页数量改变事件
    onPageSizeChange(changedPageSize) {
      this.isPageSizeChanging = true;
      new Promise(resolve => {
        this.page.pageSize = changedPageSize;
        resolve(changedPageSize)
      }).then(() => {
        this.selectPageList(this.page);
        this.isPageSizeChanging = false;
      })
    },
    //确认框确认事件
    modalTipOk() {
      this.modalLoading = true;
      if (this.modalTitle === this.operatorType[2]){
        this.deleteOrthographicImage(this.selectForm.id);
      }
    },
    //操作处理
    operatorRenderFunction(createElement, data) {
      let self = this;
      let {
        id,pid,name,url,pipelineId,projectId
      } = data.row;
      let btnList = [];
      btnList.push(createElement('Button', {
        'class': 'button-item',
        style: {
          width: '100px',
          border: '#5CADFF 1px dashed',
          color: '#5cadff'
        },
        attrs: {
          type: "dashed"
        },
        nativeOn: {
          click: function () {
            self.selectForm['id'] = id;
            self.selectForm['name'] = name;
            self.selectForm['url'] = url;
            self.selectForm['pid'] = pid;
            self.selectForm['pipelineId'] = pipelineId;
            self.selectForm['projectId'] = projectId;
            if (pid === undefined){
              self.modalTitle = self.operatorType[4];
              self.isOrthographicImageGroupAddShow = true;
            }else {
              self.modalTitle = self.operatorType[3];
              self.isOrthographicImageAddShow = true;
            }
          }
        },
      }, '修改'));
      btnList.push(createElement('Button', {
        'class': 'button-item',
        style: {
          width: '100px',
          border: '#5CADFF 1px dashed',
          color: '#FF6666'
        },
        attrs: {
          type: "dashed"
        },
        nativeOn: {
          click: function () {
            self.modalTip = true;
            self.modalTitle = self.operatorType[2];
            self.selectForm['id'] = id;
            if (url !== undefined){
              self.modalTipContent = `将要删除项目[${projectId}] 正射配置[${name}] URL[${url}],是否继续？`;
            }else {
              self.modalTipContent = `将要删除项目[${projectId}] 正射分组[${name}],是否继续？`;
            }
          }
        },
      }, '删除'));
      return createElement("div", {'class': 'r-n-c-c'}, [
        createElement('ButtonGroup', btnList),
      ])
    },
    //插入正射组
    insertOrthographicImageGroup(selectForm){
      let self = this;
      let form = {};
      form['isGroup'] = 1;
      form['name'] = selectForm['name'];
      form['projectId'] = selectForm['projectId'];
      this.$Spin.show();
      axios.post(self.url.orthographic_image_insert, form).then(function (response) {
        let {message, state} = response.data;
        if (state === 200) {
          self.selectPageList(self.page);
          self.$Message.success(message);
        } else {
          self.$Message.error(message);
        }
        self.$Spin.hide();
        self.$refs['selectGroupFormRule'].resetFields();
        self.isOrthographicImageGroupAddShow = false;
        self.selectGroupList();
      });
    },
    //插入正射地址
    insertOrthographicImage(selectForm){
      let self = this;
      let form = {};
      form['isGroup'] = 0;
      form['pid'] = selectForm['pid'];
      form['name'] = selectForm['name'];
      form['pipelineId'] = selectForm['pipelineId'];
      form['url'] = selectForm['url'];
      this.$Spin.show();
      axios.post(self.url.orthographic_image_insert, form).then(function (response) {
        let {message, state} = response.data;
        if (state === 200) {
          self.selectPageList(self.page);
          self.$Message.success(message);
        } else {
          self.$Message.error(message);
        }
        self.$Spin.hide();
        self.$refs['selectFormRule'].resetFields();
        self.isOrthographicImageAddShow = false;
      });
    },
    //删除正射地址/正射组
    deleteOrthographicImage(orthographicImageId){
      let self = this;
      axios.delete(self.url.orthographic_image_delete + orthographicImageId).then(function (response) {
        let {message, state} = response.data;
        if (state === 200) {
          self.$Message.success(message);
          if (self.page.total === (self.page.pageNum - 1) * self.page.pageSize + 1 ){
            self.page.pageNum--;
          }
          self.selectPageList(self.page);
          self.modalLoading = false;
          self.modalTip = false;
        }
      })
    },
    //更新正射组
    updateOrthographicImageGroup(selectForm){
      let self = this;
      let form = {};
      form['isGroup'] = 1;
      form['id'] = selectForm['id'];
      form['name'] = selectForm['name'];
      form['projectId'] = selectForm['projectId'];
      this.$Spin.show();
      axios.patch(self.url.orthographic_image_modify, form).then(function (response) {
        let {message, state} = response.data;
        if (state === 200) {
          self.selectPageList(self.page);
          self.$Message.success(message);
        } else {
          self.$Message.error(message);
        }
        self.$Spin.hide();
        self.$refs['selectGroupFormRule'].resetFields();
        self.isOrthographicImageGroupAddShow = false;
      });
    },
    //更新正射地址
    updateOrthographicImage(selectForm){
      let self = this;
      let form = {};
      form['isGroup'] = 0;
      form['id'] = selectForm['id'];
      form['pid'] = selectForm['pid'];
      form['name'] = selectForm['name'];
      form['pipelineId'] = selectForm['pipelineId'];
      form['url'] = selectForm['url'];
      this.$Spin.show();
      axios.patch(self.url.orthographic_image_modify, form).then(function (response) {
        let {message, state} = response.data;
        if (state === 200) {
          self.selectPageList(self.page);
          self.$Message.success(message);
        } else {
          self.$Message.error(message);
        }
        self.$Spin.hide();
        self.$refs['selectFormRule'].resetFields();
        self.isOrthographicImageAddShow = false;
      });
    },
    //查询正射组列表
    selectGroupList(){
      let self = this;
      axios.get(self.url.orthographic_image_group_list,{params: {pageSize:-1}}).then(function (response) {
        self.orthographicImageGroupList = response.data.content;
        self.orthographicImageGroupSelectList = [];
        for (let item of self.orthographicImageGroupList) {
          self.orthographicImageGroupSelectList.push(item);
        }
        if(self.orthographicImageGroupSelectList.find(((value) => value['id'] === self.selectForm['pid'])) === undefined){
          self.selectForm['pid'] = null;
        }
      }).catch(function () {
        self.isLoading = false;
      });
    },
    //查询管线列表
    selectPipelineList() {
      let self = this;
      let form = {};
      form['pageSize'] = -1;
      axios.get(self.url.pipeline_list, {params: form}).then((response)=>{
        self.pipelineList = response.data.content.records;
      });
    },
    //查询正射列表
    selectPageList(selectForm) {
      let self = this;
      let form = Object.assign({}, selectForm);
      if (self.searchKey !== null && self.searchValue !== null && self.searchValue !== ""){
        form[self.searchKey] = self.searchValue.trim();
      }
      self.isLoading = true;
      axios.get(self.url.orthographic_image_list, {params: form}).then(function (response) {
        let {records,total} = response.data.content;
        self.page.total = total;
        self.dataList = records;
        self.isLoading = false;
      }).catch(function () {
        self.isLoading = false;
      });
    }
  }
}
</script>

<style scoped>
#content {
  background: #FFFFFF;
  padding: 15px;
  overflow: auto;
}

.item-input {
  height: 45px;
  line-height: 45px;
  margin-bottom: 10px;
}

.item-input-span {
  /*height: inherit;*/
  width: 120px;
}

.item-key {
  /*height: inherit;*/
  width: 150px;
}
.item-value {
  /*height: inherit;*/
  width: 50px;
}

.ivu-form-item-content {
  margin-left: 0 !important;
  position: relative;
  line-height: 32px;
  font-size: 14px;
}

.ivu-form-item {
  margin-bottom: 0;
  width: 100%;
}

.button-item {
  border: #19be6b 1px dashed;
  color: #19be6b;
}

.filter-item {
  margin: 0 5px;
}

.demo-spin-icon-load{
  animation: ani-demo-spin 1s linear infinite;
}
@keyframes ani-demo-spin {
  from { transform: rotate(0deg);}
  50%  { transform: rotate(180deg);}
  to   { transform: rotate(360deg);}
}
.demo-spin-col{
  height: 20px;
  position: relative;
}
</style>